<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.username" placeholder="用户名" clearable />
          <el-input v-model="searchModel.phone" placeholder="电话" clearable />
          <el-button type="primary" round icon="el-icon-search" @click="getUserList">查询</el-button>
        </el-col>
        <el-col :span="4" align="right">
          <el-button type="primary" icon="el-icon-plus" circle @click="openEditUI(null)" />
        </el-col>
      </el-row>
    </el-card>

    <!-- 渲染列表 -->
    <el-card>
      <el-table :data="userList" stripe style="width: 100%">
        <el-table-column type="index" label="#" width="80">
          <template slot-scope="scope">
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="用户ID" width="100" />
        <el-table-column prop="avatar" label="头像" width="100">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="60" height="60">
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="130" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="status" label="用户状态" width="150">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 1 ">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="电子邮件" width="200" />
        <el-table-column prop="money" label="金额" width="130" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="min" circle @click="openEditUI(scope.row.id)" />
            <el-button v-if="scope.row.username !== 'admin'" type="danger" icon="el-icon-delete" size="min" circle @click="deleteUser(scope.row)" />
            <el-tag v-else>超级管理员</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!--新增用户-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearForm">
      <el-form ref="userFormRef" :model="userFrom" :rules="rules">
        <el-form-item prop="username" label="用户名" :label-width="formLabelWidth">
          <el-input v-model="userFrom.username" auto-complete="off" />
        </el-form-item>
        <el-form-item v-if="userFrom.id == null || userFrom.id == undefined" prop="password" label="登录密码" :label-width="formLabelWidth">
          <el-input v-model="userFrom.password" type="password" auto-complete="off" />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="userFrom.phone" auto-complete="off" @input="(v)=>(userFrom.phone=v.replace(/[^\d]/g,''))" />
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-switch v-model="userFrom.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-checkbox-group
            v-model="userFrom.roleIdList"
            style="width: 85%;"
            :max="2"
          >
            <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleDesc }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="email" label="电子邮件" :label-width="formLabelWidth">
          <el-input v-model="userFrom.email" auto-complete="off" />
        </el-form-item>
        <el-form-item prop="money" label="金额" :label-width="formLabelWidth">
          <el-input v-model="userFrom.money" auto-complete="off" @input="(v)=>(userFrom.money=v.replace(/[^\d.]/g,''))" />
        </el-form-item>
        <el-form-item class="hide" prop="complain" label="是否被举报" :label-width="formLabelWidth">
          <el-input v-model="userFrom.complain" :placeholder="0" auto-complete="off" readonly />
        </el-form-item>
        <el-form-item class="hide" prop="cause" label="举报原因" :label-width="formLabelWidth">
          <el-input v-model="userFrom.cause" :placeholder="'无'" auto-complete="off" readonly />
        </el-form-item>
        <el-form-item class="hide" prop="complainer" label="举报人" :label-width="formLabelWidth">
          <el-input v-model="userFrom.complainer" :placeholder="'无'" auto-complete="off" readonly />
        </el-form-item>
        <el-form-item class="hide" prop="message" label="信息" :label-width="formLabelWidth">
          <el-input v-model="userFrom.message" :placeholder="'无'" auto-complete="off" readonly />
        </el-form-item>
        <el-form-item v-if="userFrom.id != null && userFrom.id != undefined" prop="avatar" label="头像" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8088/user"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userFrom.avatar" :src="userFrom.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/userManage'
import roleApi from '@/api/roleManage'
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'))
      }
      callback()
    }
    return {
      roleList: [],
      formLabelWidth: '130px',
      userFrom: {
        roleIdList: []
      },
      dialogFormVisible: false,
      title: '',
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 5
      },
      userList: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', tigger: 'blur' },
          { min: 3, max: 10, message: '长度在3到10个字符', tigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录初始密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮件', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        money: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
    this.getAllRoleList()
  },
  methods: {
    getAllRoleList() {
      roleApi.getAllRoleList().then(response => {
        this.roleList = response.data
      })
    },
    deleteUser(user) {
      this.$confirm(`您确认删除用户${user.username} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.deleteUserById(user.id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveUser() {
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 提交请求到后台
          this.$set(this.userFrom, 'complain', 0)
          this.$set(this.userFrom, 'complainer', '无')
          this.$set(this.userFrom, 'cause', '无')
          this.$set(this.userFrom, 'message', '无')
          this.$set(this.userFrom, 'flag', 0)
          userApi.saveUser(this.userFrom).then(response => {
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            // 刷新表格
            this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearForm() {
      this.userFrom = {
        roleIdList: []
      }
      this.$refs.userFormRef.clearValidate()
    },
    openEditUI(id) {
      if (id == null) {
        this.title = '新增用户'
      } else {
        this.title = '修改用户'
        // 根据id查询用户数据
        userApi.getUserById(id).then(respose => {
          this.userFrom = respose.data
        })
      }
      this.dialogFormVisible = true
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getUserList()
    },
    getUserList() {
      userApi.getUserList(this.searchModel).then(response => {
        this.userList = response.data.rows
        this.total = response.data.total
      })
    },
    BlobToBase64(image) {
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        this.userFrom.avatar = canvas.toDataURL() // 图片的base64地址
        console.log(this.userFrom.avatar)
        this.$set(this.userFrom, 'avatar', this.userFrom.avatar)
        userApi.updateUser(this.userFrom).then(response => {
        })
        console.log(this.userFrom.avatar)
      }
    },
    handleAvatarSuccess(res, file) {
      // bolb转base64
      const image = new Image() // 新建一个img标签（还没嵌入DOM节点)
      image.src = URL.createObjectURL(file.raw)
      this.BlobToBase64(image)
      // this.userFrom.avatar = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
#search .el-input {
  width: 200px;
  margin-right: 20px;
}
.el-dialog{
  position: absolute;
  top: -70px;
  right: 0;
}
.el-dialog .el-input {
  width: 85%;
}
.hide{
  display: none;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 15px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
